function classNames( classes ){
    var className = ''

    for( var key in classes ){
        if ( classes[key] ) {
            className += key + ' '
        }
    }

    return className.trim()
}
var TodoItem = React.createClass({
    getInitialState: function() {
        return {
            done: this.props.todo.done,
            editing: false,
            title: this.props.todo.title
        }
    },
    edit: function( value ){
        this.setState({editing: value})
    },
    change: function( event ){
        this.setState({title:event.target.value})
    },
    blur: function( event ){
        this.setState({editing: false, title: event.target.value.trim()})
        this.props.onEdit( event.target.value.trim() )
    },
    componentDidUpdate: function () {
        var node = ReactDOM.findDOMNode(this.refs.editField);
        node.focus();
    },
    enter: function( event ){
        if ( event.keyCode == ENTER_KEY ) {
            this.blur(event)
        }
    },
    render: function(){
        var className = classNames({
            'done': this.props.todo.done,
            'editing': this.state.editing
        })
        return (
                <li className={className}>
                    <div className="view">
                        <input type="checkbox"
                            checked={this.props.todo.done}
                            onChange={this.props.onToggle}
                        />
                        <label onDoubleClick={this.edit}>{this.props.todo.title}</label>
                        <button onClick={this.props.onDel}>X</button>
                    </div>
                    <input type="text"
                        ref="editField"
                        value={this.state.title}
                        onChange={this.change}
                        onBlur={this.blur}
                        onKeyDown={this.enter}
                    />
                </li>
            )
    }
})

var App = React.createClass({
    getInitialState: function () {
        return {
            newTodo: '',
            hash: ''
        }
    },
    componentDidMount: function() {
        var self = this
        setInterval( function(){
            var hash = location.hash.replace('#/', '');
            if ( self.state.hash !== hash ) {
                self.setState( { hash:hash } )
            }
        }, 100 )
    },
    add: function( event ){
        if ( event.keyCode != ENTER_KEY || !event.target.value.trim() ) {
            return
        }
        this.props.lists.push( {
                id: this.props.lists.length,
                title: event.target.value,
                done: false
            } )
        
        this.setState({newTodo:''})

        this.save( this.props.lists )
    },
    change: function( event ){
        this.setState({newTodo:event.target.value})
    },
    del: function( todo, index ){
        this.props.lists.splice( index, 1 )
        this.save( this.props.lists )
    },
    toggle: function( todo, index ){        // completed or not
        this.props.lists[index].done = !this.props.lists[index].done
        this.save( this.props.lists )
    },
    edit: function( index, newTitle ){
        this.props.lists[index].title = newTitle
        this.save( this.props.lists )
    },
    clearCompleted: function(){
        var uncompleted_lists = this.props.lists.filter(function(elem, index) {
            return !elem.done
        });
        this.save( uncompleted_lists )
    },
    save: function( lists ){
        localStorage.setItem( STORAGE_KEY, JSON.stringify( lists ) )
        render()
    },
    render: function() {
        var completed_lists = this.props.lists.filter(function( ele ){
            return ele.done
        })

        var unCompletedLength = this.props.lists.length - completed_lists.length

        if ( completed_lists.length > 0 ) {
            var clear = (<button onClick={this.clearCompleted}>clear completed</button>)
        }

        var showLists = this.props.lists.filter( function( ele ){
            switch( this.state.hash ){
                case 'active':
                    return ele.done === false
                    break;
                case 'completed':
                    return ele.done === true
                    break;
                default :
                    return true;
            }
        }, this );

        var todos = showLists.map(function(todo, index) {
                        return  (
                                <TodoItem
                                    key={index}
                                    todo={todo}
                                    onDel={this.del.bind(this, todo, index)}
                                    onToggle={this.toggle.bind(this, todo, index)}
                                    onEdit={this.edit.bind(this, index)}
                                />
                            )
                    }, this)
        var hash = this.state.hash
        return (
            <div>
                <h1>todos</h1>
                <input
                    placeholder="What needs to be done?"
                    onKeyDown={this.add}
                    onChange={this.change}
                    value={this.state.newTodo}
                />
                <ul className="todos">
                    {todos}
                </ul>
                <footer>
                    {unCompletedLength} item left
                    <a href="#/" className={classNames({selected:!hash})}>All</a>
                    <a href="#/active" className={classNames({selected:hash === 'active'})}>Active</a>
                    <a href="#/completed" className={classNames({selected:hash === 'completed'})}>Completed</a>
                    {clear}
                </footer>
            </div>
            )
    }
});

function render(){
    var lists = JSON.parse( localStorage.getItem( STORAGE_KEY ) ) || []

    ReactDOM.render(
        <App lists={lists} />,
        document.getElementById('app')
    );
}

var STORAGE_KEY = 'todos'
var ENTER_KEY = 13

render();